using System;
using System.ServiceProcess;
using System.Timers;
using Microsoft.Health.Samples.PatientConnect.ContosoHealth.HealthVaultAdapter;

namespace Microsoft.Health.Samples.PatientConnect.ContosoHealth.ContosoHealthScheduler
{
    public partial class ContosoService : ServiceBase
    {       
        /// <summary>
        /// Timer to run the scheduler at specified time interval.
        /// </summary>
        private Timer _timer;

        ServiceInboundCalls _inboundCalls = new ServiceInboundCalls();
        ServiceOutboundCalls _outboundCalls = new ServiceOutboundCalls();

        /// <summary>
        /// Constructor
        /// </summary>
        public ContosoService()
        {
            InitializeComponent();
        }                 
        
        /// <summary>
        /// Service's OnStart event
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            long timerValue = 0;
            try
            {
                timerValue = ServiceInboundCalls.CalculateTimerValue();
                _timer = new Timer(timerValue);
                _timer.Elapsed += TimerElapsed;
                _timer.AutoReset = false;
                _timer.Enabled = true;
                _timer.Start();
            }
            catch (Exception ex)
            {
                Logger.LogEvent(ex.Message, SchedulerStatus.Error);
            }
        }
        
        /// <summary>
        /// Timer elapsed event of the scheduler.
        /// </summary>
        /// <param name="sender">object</param>
        /// <param name="e">ElapsedEventArgs</param>
        protected void TimerElapsed(object sender, ElapsedEventArgs e)
        {
            
            try
            {
                Logger.LogEvent("Scheduler started at: " + DateTime.Now + Environment.NewLine, SchedulerStatus.Started);
                ServiceInboundCalls.CallInboundMethods();
            }
            catch (Exception ex)
            {
                Logger.LogEvent(ex.Message, SchedulerStatus.Error);
            }
            try
            {
                ServiceOutboundCalls.CallOutboundMethods();
                Logger.LogSchedulerLastRun();
            }
            catch (Exception ex)
            {
                Logger.LogEvent(ex.Message, SchedulerStatus.Error);
            }
            _timer.Start();
        }
    }
}
